package com.itheima.Interceptor;

import com.alibaba.fastjson2.JSON;
import com.itheima.common.ThreadLocalUtil;
import com.itheima.dto.UserlogInDto;
import com.itheima.exception.TokenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author :WuJunJie
 * packageName :com.itheima.Interceptor
 * fileName :TokenInterceptor
 * creationTime :2022-11-25 20:41
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("AuthorizationUser");
//        log.info("{}",token);
        Object o = redisTemplate.opsForValue().get("user_token:" + token);
        if(o==null){
            throw new TokenException("没有token或token已失效");
        }
        UserlogInDto userlogInDto = JSON.parseObject(o.toString(), UserlogInDto.class);
        ThreadLocalUtil.setid(userlogInDto.getId());
        redisTemplate.opsForValue().set("user_token:"+token,JSON.toJSONString(userlogInDto),30, TimeUnit.MINUTES);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
